<template>
  <div v-loading="loading" class="container">
    <div class="app-container">
      <el-tree :data="depts" :props="defaultProps" default-expand-all :expand-on-click-node="false">
        <!-- 布局组件 el-row-el-col -->
        <!-- 插槽 -->
        <template v-slot="{ data }">
          <el-row style="width: 100%; height: 40px;" align="middle" type="flex">
            <el-col>{{ data.name }}</el-col>
            <el-col>
              <el-row type="flex" justify="end">
                <span class="username">{{ data.managerName }}</span>
                <el-dropdown :hide-on-click="false" @command="operateDept($event,data.id)">
                  <span class="username">操作<i class="el-icon-arrow-down" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <ShowDialog ref="addForm" :show-dialog.sync="ifShowDialog" :pid="currentID" @updateDept="getDepts" />
  </div></template>
<script>
import { getDepartmentMsgAPI } from '@/api/department'
import { listTransformTree } from '@/utils'
import ShowDialog from './components/ShowDialog.vue'

export default {
  name: 'Department',
  components: {
    ShowDialog
  },
  data() {
    return {
      loading: false,
      currentID: null,
      ifShowDialog: false,
      depts: [], // 组织架构数据
      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    async getDepts() {
      this.loading = true
      this.depts = listTransformTree(await getDepartmentMsgAPI(), 0)
      this.loading = false
    },
    async operateDept(value, id) {
      if (value === 'add') {
        this.ifShowDialog = true
        this.currentID = id
      } else if (value === 'edit') {
        this.currentID = id
        // nextTick会等到组件的上一次更新完成之后执行
        this.$nextTick(() => {
          // $refs可以获取到该组件的方法
          this.$refs.addForm.getDeptDetail(this.currentID)
        })
        this.ifShowDialog = true
      } else {
        await this.$confirm('确定要删除吗?')
        this.currentID = id
        this.$refs.addForm.deleteDeptDetail(this.currentID)
      }
    }
  }
}
</script>
<style scoped>
  .app-container {
    padding: 20px 50px;
  }
  .username {
    margin-right: 10px;
    font-size: 14px;
  }
</style>
